<template>
    <div v-if="skeletonLoadingAnimation" :class="containerClass">
        <Skeleton class="h-[100px] mb-2 py-3 mx-4 rounded-2xl bg-black/10" />
    </div>
    <div v-else :class="containerClass">
        <div class="backdrop-blur-sm bg-white/80 rounded-2xl py-3 mx-4 flex flex-col ">
            <!-- 输入框 -->
            <SmartTextarea
                v-model="userMessage"
                ref="textareaRef"
                :placeholder="placeholder"
                :minRows=minRows
                :maxRows=maxRows
                :customCss="smartTextareaClass"
                @enterPressed="handleSendMessage"
                >
            </SmartTextarea>

            <!-- 下方容器 -->
            <div class="flex mx-3 mt-3">
                <div class="flex gap-3 relative">
                    <!-- 大模型下拉框菜单 -->
                    <ChatInputBoxDropdownMenu 
                      :icon="currSelectedTextModel?.provider"
                      :name="currSelectedTextModel?.name">
                        <!-- 插槽下拉模型列表-->
                        <div v-for="model in textModels" :key="model.id" 
                            class="px-3 py-2 gap-1 hover:bg-gray-100 cursor-pointer flex items-center"
                            @click="selectTextModel(model)">
                            <div class="flex-1 flex items-center">
                                <!-- 模型图标 -->
                                <SvgIcon :name="model.provider" class="w-5 h-5 mr-2 shrink" />
                                <!-- 模型描述 -->
                                <div class="flex flex-col text-xs">
                                    <div class="text-gray-800 whitespace-nowrap">{{ model.name }}</div>
                                    <div class="text-gray-500 whitespace-nowrap">由 {{ model.provider }} 提供</div>
                                    <div v-show="model.description" class="text-gray-500 line-clamp-1 text-[10px] whitespace-nowrap">{{ model.description }}</div>
                                </div>
                            </div>

                            <SvgIcon v-if="model.selected" name="check" class="w-4 h-4 text-gray-600 shrink"></SvgIcon>
                            <!-- 用于占位 -->
                            <div v-else class="w-4 h-4 shrink-0"></div>
                        </div>
                    </ChatInputBoxDropdownMenu>

                    <!-- 语音模型下拉框 和 语言下拉框 -->
                    <div v-show="soundModels?.length > 0" class="flex gap-3">
                      <!-- 语音模型下拉框菜单 -->
                      <ChatInputBoxDropdownMenu 
                        icon="soundwave"
                        iconColor="text-[#798FFF]"
                        :name="currSelectedSoundModel?.modelName + ' ' + currSelectedSoundModel?.version">
                          <!-- 插槽下拉模型列表-->
                          <div v-for="model in soundModels" :key="model.id" 
                              class="px-3 py-2 gap-1 hover:bg-gray-100 cursor-pointer flex items-center"
                              @click="selectSoundModel(model)">
                              <div class="flex-1 flex items-center">
                                  <!-- 模型图标 -->
                                  <SvgIcon name="soundwave" class="w-5 h-5 mr-2 shrink text-[#798FFF]" />
                                  <!-- 模型描述 -->
                                  <div class="flex flex-col text-xs">
                                      <div class="text-gray-800 whitespace-nowrap w-auto overflow-visible">{{ model.modelName + ' ' + model.version }}</div>
                                      <div v-show="model.modelDescription" class="text-gray-500 line-clamp-1 text-[10px]">{{ model.modelDescription }}</div>
                                  </div>
                              </div>

                              <SvgIcon v-if="model.selected" name="check" class="w-4 h-4 text-gray-600 shrink"></SvgIcon>
                              <!-- 用于占位 -->
                              <div v-else class="w-4 h-4 shrink-0"></div>
                          </div>
                      </ChatInputBoxDropdownMenu>

                      <!-- 语言下拉框菜单 -->
                      <ChatInputBoxDropdownMenu 
                        icon="translate"
                        iconColor="text-[#FFA1A1]"
                        :name="currSelectedSoundModel?.language?.name">
                          <!-- 插槽下拉模型列表-->
                          <div v-for="language in currSelectedSoundModelLanguages" :key="language.id" 
                              class="px-3 py-2 gap-1 hover:bg-gray-100 cursor-pointer flex items-center"
                              @click="selectSoundModelLanguage(language)">
                              <div class="flex-1 flex items-center">
                                  <!-- 图标 -->
                                  <SvgIcon name="translate" class="w-5 h-5 mr-2 shrink text-[#FFA1A1]" />
                                  <!-- 描述 -->
                                  <div class="flex flex-col text-xs">
                                      <div class="text-gray-800 whitespace-nowrap w-auto overflow-visible">{{ language.name }}</div>
                                  </div>
                              </div>

                              <SvgIcon v-if="language.selected" name="check" class="w-4 h-4 text-gray-600 shrink"></SvgIcon>
                              <!-- 用于占位 -->
                              <div v-else class="w-4 h-4 shrink-0"></div>
                          </div>
                      </ChatInputBoxDropdownMenu>
                    </div>

                    <!-- 联网搜索 -->
                    <div class="border px-2 py-1 rounded-3xl flex items-center justify-center cursor-pointer transition-all duration-300 ease-in-out active:scale-90"
                        :class="isNetworkSearchSelected ? 'border-[#E2EAFD] bg-[#E2EAFD] hover:bg-[#E2EAFD]/70 text-[#6881FF]' : 'text-gray-800 border-gray-300 hover:bg-gray-200/30'"
                        @click="toggleNetworkSearch">
                        <Icon icon="mingcute:earth-2-line" class="w-5 h-5 mr-1.5"/>
                    
                        <span class="mr-1 text-xs text-center">联网搜索</span>
                    </div>

                    <!-- 深度思考 -->
                    <div v-show="currSelectedTextModel.isSelectThink" class="border px-2 py-1 rounded-3xl flex items-center justify-center cursor-pointer transition-all duration-300 ease-in-out active:scale-90"
                        :class="isThinkSelected ? 'border-[#FFE8E8] bg-[#FFE8E8] hover:bg-[#FFE8E8]/70 text-[#FFA1A1]' : 'text-gray-800 border-gray-300 hover:bg-gray-200/30'"
                        @click="toggleThink">
                        <SvgIcon name="think" class="w-5 h-5 mr-1.5"/>
                    
                        <span class="mr-1 text-xs text-center">深度思考</span>
                    </div>
                </div>

                <!-- 中间占位 -->
                <div class="grow"></div>

                <!-- 发送按钮 -->
                <div class="flex items-center">
                    <button 
                        class="flex items-center justify-center bg-[#4d6bfe] rounded-lg px-4 py-1 gap-2
                        hover:bg-[#3b5bef] transition-colors
                        disabled:opacity-50
                        disabled:cursor-not-allowed"
                        @click="handleSendMessage"
                        :disabled="!userMessage.trim()">

                        <span class="text-sm text-[#ffffff]">发送</span>
                    </button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { Icon } from '@iconify/vue';
import { computed, defineProps, ref  } from 'vue'
import SvgIcon from '../common/SvgIcon.vue';
import SmartTextarea from '../common/SmartTextarea.vue'
// 导入Pinia store
import { useChatStore } from '@/stores/chatStore'
import { useRoleChatStore } from '@/stores/roleChatStore'
import Skeleton from '@/components/common/Skeleton.vue'
import ChatInputBoxDropdownMenu from './ChatInputBoxDropdownMenu.vue';
import { useRoute } from 'vue-router'

const route = useRoute()
// 获取 chat store
const chatStore = useChatStore()
// 获取 roleChat store
const roleChatStore = useRoleChatStore()

// 获取路由里的角色ID
const roleId = computed(() => {
  // 获取路由参数
  const id = route.query?.roleId
  // 转为数字
  return id ? Number(id) : 1
})
// 当前选择的文本模型，优先角色上下文，否则回退到全局选择
const currSelectedTextModel = computed(() => {
  // 获取角色ID
  const id = roleId.value
  // 说明是系统角色
  if (id === 1) {
    // 获取全局选择的模型
    return chatStore.selectedModel
  }
  // 获取角色选择的模型
  const selected = roleChatStore.findSelectedRoleModelList(id)
  if (!selected) {
    // 如果角色ID不存在，则返回全局选择
    return chatStore.getSelectedModel(props.textModels)
  }

  return selected?.textModel
})

// 当前选择的语音模型，基于角色上下文，缺省时提供空占位
const currSelectedSoundModel = computed(() => {
  // 获取角色ID
  const id = roleId.value
  // 查找角色选择的模型
  const selected = roleChatStore.findSelectedRoleModelList(id)

  return selected?.soundModel
})

// 当前选择的语言模型里的语言信息
const currSelectedSoundModelLanguages = computed(() => {
  // 获取选中的模型ID
  const id = currSelectedSoundModel.value?.id

  // 查询出语言模型支持的语言列表
  return props.soundModels?.find(model => model.id === id)?.languages
})

// 是否启用联网搜索，使用 chatStore 中的状态
const isNetworkSearchSelected = computed(() => chatStore.isNetworkSearchSelected)

// 是否启用深度思考
const isThinkSelected = computed(() => chatStore.isThinkSelected)

// 接收父组件传递的属性
const props = defineProps({
  // textarea 中用户输入的用户消息
  modelValue: {
    type: String,
    required: true
  },
  textModels: {
    type: Array,
    default: []
  },
  soundModels: {
    type: Array,
    default: []
  },
  placeholder:{
    type: String,
    default: '给黑夜 AI 机器人发送消息'
  },
  smartTextareaClass:{
    type: String,
    default: ''
  },
  minRows: {
    type: Number,
    default: 2
  },
  maxRows: {
    type: Number,
    default: 14
  },
 // 自定义根容器样式
  containerClass: {
    type: String,
    default: ''
  },
  // 模型下拉框加载动画
  skeletonLoadingAnimation: {
    type: Boolean,
    default: true
  }
})

// 定义 emits
const emit = defineEmits(['update:modelValue', 'sendMessage'])

// 计算属性，用于 v-model 的双向绑定
const userMessage = computed({
  get() {
    return props.modelValue;
  },
  set(value) {
    emit('update:modelValue', value);
  }
})

// 处理发送消息
const handleSendMessage = () => {
    // 若消息为空
    if (!userMessage.value.trim()) {
        message.warning('消息不能为空');
        return;
    }

    if (roleId.value === 1) {
      // 系统角色，使用 chatStore 中的模型
      emit('sendMessage', {
        selectedModel: chatStore.selectedModel,
        isNetworkSearch: chatStore.isNetworkSearchSelected,
        thinkEnable: chatStore.isThinkSelected
      });
    } else {
      // 非系统角色，使用 roleChatStore 中的模型
      emit('sendMessage', {
        selectedTextModel: currSelectedTextModel.value,
        selectedSoundModel: currSelectedSoundModel.value,
        isNetworkSearch: chatStore.isNetworkSearchSelected,
      });
    }

    // 清空输入框
    userMessage.value = '';
}

// 选择文本模型
const selectTextModel = (model) => {
    // 当前角色是系统角色，
    if (roleId.value === 1) {
      // 更新 chatStore 中的选中模型
      chatStore.updateSelectedModel(model);
    } else { 
      // 更新 roleChatStore 中的选中模型
      roleChatStore.updateSelectedRoleTextModel(roleId.value, model)
    }

    // 将所有模型的 selected 置为 false 除被选中模型
    props.textModels.forEach(m => {
      m.selected = m.id === model.id
    });
}

// 选择语音模型
const selectSoundModel = (model) => {
    // 当前角色是系统角色，
    if (roleId.value === 1) {
      // 更新 chatStore 中的选中模型
      chatStore.updateSelectedModel(model);
    } else { 
      // 更新 roleChatStore 中的选中模型
      roleChatStore.updateSelectedRoleSoundModel(roleId.value, model)
    }

    // 将所有模型的 selected 置为 false 除被选中模型
    props.soundModels.forEach(m => {
      m.selected = m.id === model.id
    });
}

// 获取语音模型中的语言
const selectSoundModelLanguage = (lang) => {
  // 更新 roleChatStore 中的选中模型语言
  roleChatStore.updateSelectedSoundModelLanguage(roleId.value, lang)

  // 将所有语音模型的语言 selected 置为 false 除被选中模型
  const soundModelId = currSelectedSoundModel.value.id
  // 获取当前选中的语音模型
  const index = props.soundModels.findIndex(m => m.id === soundModelId)

  if (index !== -1) {
    props.soundModels[index].languages.forEach(language => {
      language.selected = language.id === lang.id
    });
  }
}
// 切换联网搜索选中状态
const toggleNetworkSearch = () => {
    // 更新 store 中的联网搜索状态
    chatStore.updateNetworkSearchStatus(!chatStore.isNetworkSearchSelected)
}

// 切换思考选中状态
const toggleThink = () => { 
      // 更新 store 中的思考状态
    chatStore.updateThinkStatus(!chatStore.isThinkSelected)
}
</script>

<style scoped>

</style>